﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using BusinessEntity;
using BusinessRule;
using BusinessRule.Scheduling;
using learun.util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Nacos.AspNetCore;
using ProjectManApi.Extensions;

namespace ProjectManApi.Controllers
{
    public class XMListController : MvcControllerBase
    {
        private readonly INacosServerManager _serverManager;
        public XMListController(INacosServerManager serverManager)
        {
            _serverManager = serverManager;
        }


        [HttpPost]
        public IActionResult Index()
        {
            return View();
        }


        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetFWZL()
        {
            var baseUrl = _serverManager.GetServerAsync("ic-auth").GetAwaiter().GetResult(); ;

            if (string.IsNullOrWhiteSpace(baseUrl))
            {
                return Fail("empty");
            }

            //var url = $"{baseUrl}/oauth/check_token";
            //http://{{BASE_URL}}/auth/oauth/token?grant_type=password

            var url = $"{baseUrl}/oauth/check_token";

            using (HttpClient client = new HttpClient())
            {


                string clientInfo = "test:test";
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(clientInfo);
                clientInfo = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

                client.DefaultRequestHeaders.Add("Authorization", "Basic " + clientInfo);
                //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//ACCEPT header
                //client.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh;");

                //http://{{BASE_URL}}/auth/oauth/token?grant_type=password
                //http://{{BASE_URL}}/oauth/check_token
                //http://118.190.140.38:3000/token/login

                url = url.Replace("172.31.162.64:3000", "118.190.140.38:3000");
                //client.BaseAddress = new Uri(url);
                //设置请求体中的内容，并以post的方式请求
                //token=697d2737-fe50-49b2-82c8-33ff2932d28a
                //var response = await client.PostAsync(url, new StringContent("token=697d2737-fe50-49b2-82c8-33ff2932d28a"));

                var data = Encoding.UTF8.GetBytes("token=237152b1-4d47-413b-a0e9-6db09ea939f5");
                var content = new ByteArrayContent(data);
                content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");

                var response = await client.PostAsync(url, content);


                //获取请求到数据，并转化为字符串
                var result = response.Content.ReadAsStringAsync().Result;
                var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(result);// result.ToJson();


                return Success(Jresult["user_info"]);
            }

            //return Content("empty");
        }

        /// <summary>
        /// 授权
        /// </summary>
        /// <param name="scid"></param>
        /// <returns></returns>
        [HttpPost]
        //[Authorize(Policy = "TestPolicy")]
        //[AllowAnonymous]
        public async Task<IActionResult> GetListByScidAsync(string scid)
        {
            //(DataTable, int) SelectTable = await XMListRule.GetXMList(scid, GetUserId(), null, "id", true, 20, 1);

            //return Success(SelectTable);

            return Success("");
        }

        //测试增删改查
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> GetXMFindUpdateDel()
        {
            //await XMListRule.GetXMFindUpdateDel();
            return Success("成功");
        }

        /// <summary>
        /// 事务提交方法1
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> GetXMSaveAsync1()
        {
            List<string> lists = new List<string>();
            string strsql = "insert into CProTB(id) values('1') ";

            lists.Add(strsql);
            strsql = "insert into CProTB(id) values('2') ";
            lists.Add(strsql);
            strsql = "insert into CProTB(id) values('3') ";
            lists.Add(strsql);

            strsql = "insert into CProTB(id) values('4') ";
            lists.Add(strsql);

            for (int i = 0; i < 1000; i++)
            {
                string strid = CommonHelper.GetUniqueId().ToString();
                strsql = "insert into CProTB(id) values('" + strid + "') ";
                lists.Add(strsql);
            }


            //bool bb = await XMListRule.GetXMSaveTransAsync(lists);


            return Success("成功");
        }

        /// <summary>
        /// 事务提交方法2
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> GetXMSaveAsync2()
        {
            List<string> lists = new List<string>();
            string strsql = "insert into CProTB(id) values('hh11') ";

            lists.Add(strsql);
            strsql = "insert into CProTB(id) values('hh12') ";
            lists.Add(strsql);
            strsql = "insert into CProTB(id) values('hh13') ";
            lists.Add(strsql);

            strsql = "insert into CProTB(id) values('hh14') ";
            lists.Add(strsql);

            for (int i = 0; i < 1000; i++)
            {
                string strid = "hh" + CommonHelper.GetUniqueId().ToString();
                strsql = "insert into CProTB(id) values('" + strid + "') ";
                lists.Add(strsql);
            }

            //保存list方法1
            //bool bbc = await XMListRule.GetXMSaveTransFuncAsync(lists);

            //await Query.GetRunActionTransAsync(async iRep =>
            //{
            //    for (int i = 0; i < lists.Count; i++)
            //    {
            //        await iRep.ExecuteSql(lists[i]);
            //    }
            //    return true;
            //});

            //保存保存list方法2
            //await XMListRule.GetXMSaveTransFuncAsync2(async (iRep) =>
            //{
            //    for (int i = 0; i < lists.Count; i++)
            //    {
            //        await iRep.ExecuteSql(lists[i]);//GetAwaiter()

            //    }
            //    return true;
            //});

            return Success("成功");
        }

        /// <summary>
        /// //这个是任务调度
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task GetTrySchedule()
        {
            //定时器
            Businessutil.CronDaemon CronDaemon = new Businessutil.CronDaemon();
            CronDaemon.AddJob("*/2 * * * * ? *", () =>
            {
                string strs = "定时器";
            });
            CronDaemon.Start();

            //任务调度
            await QuartzHelper.InitJob();//.GetAwaiter()
        }

        [HttpGet]
        [AllowAnonymous]
        public IActionResult GetTryLock3()//这个分布式锁不等待
        {
            //RedisValue
            string Token = Environment.MachineName;

            string cc = new BusinessCache.RedisCache().GetLock2("c", Token, TimeSpan.FromSeconds(6));//new TimeSpan(1000)

            return Success(cc);
        }

        [HttpGet]
        [AllowAnonymous]
        public IActionResult GetTryLock()//这个分布式锁不等待
        {
            List<string> lists = new List<string>();
            List<Task<string>> ll = new List<Task<string>>();
            for (int i = 0; i < 100; i++)
            {
                ll.Add(Task.Factory.StartNew(a =>
                {
                    string sstime = DateTime.Now.ToMillisecondString();
                    var cc = new BusinessCache.CacheByRedis().CreateLockTake("cs");//.GetAwaiter()
                    if (cc)
                    {
                        return sstime + "成功(" + a.ToString() + "||" + cc.ToString() + ")                                     ";
                    }
                    else
                    {
                        return sstime + "超时(" + a.ToString() + "||" + cc.ToString() + ")                                     ";
                    }
                }, i.ToString())
                    );
            }

            for (int i = 0; i < ll.Count; i++)
            {
                lists.Add(ll[i].Result);
                ll[i].Wait();
            }

            //Task.WaitAll(ll.ToArray());

            return Success(lists);
        }

        /// <summary>
        /// 分布式锁
        /// </summary>
        /// <returns></returns>
         //@ApiOperation(value= "用户controller", tags={ "用户操作接口"})
        [HttpGet]
        [AllowAnonymous]
        public IActionResult GetTryLock2()//这个分布式锁等待
        {
            List<string> lists = new List<string>();
            List<Task<string>> ll = new List<Task<string>>();
            for (int i = 0; i < 200; i++)
            {
                ll.Add(Task.Factory.StartNew(a =>
                {
                    BusinessCache.LockByRedis lbr = new BusinessCache.LockByRedis();
                    string sstime = DateTime.Now.ToMillisecondString();
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();  //启动Stopwatch
                    var cc = lbr.TryLock("cs", 10, 1);//.GetAwaiter()
                    stopwatch.Stop();  //停止Stopwatch
                    if (cc)
                    {
                        System.Threading.Thread.Sleep(90);

                        lbr.TryDelLock("cs");

                        return sstime + "成功(" + a.ToString() + "||" + cc.ToString() + ")耗时：" + stopwatch.ElapsedMilliseconds + "                                     ";

                    }
                    else
                    {
                        return sstime + "超时(" + a.ToString() + "||" + cc.ToString() + ")耗时：" + stopwatch.ElapsedMilliseconds + "                                     ";
                    }
                }, i.ToString())
                    );
            }

            for (int i = 0; i < ll.Count; i++)
            {
                lists.Add(ll[i].Result);
                ll[i].Wait();
            }

            //Task.WaitAll(ll.ToArray());

            return Success(lists);
        }

    }
}